package com.typy.www.tpay.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;

import com.typy.www.tpay.R;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ImageUtils {
	
	/**
	 * 写图片文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/cache 目录下
	 * 
	 * @throws IOException
	 */
	public static File saveImage(Context context, String fileName, Bitmap bitmap)
			throws IOException {
		return saveImage(context, fileName, bitmap, 100);
	}

	public static File saveImage(Context context, String fileName,
                                 Bitmap bitmap, int quality) throws IOException {
		if (bitmap == null || fileName == null || context == null)
			return null;

//		FileOutputStream fos = context.openFileOutput(fileName,
//				Context.MODE_PRIVATE);
		File file = new File(context.getCacheDir().toString() + File.separator + fileName);
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, quality, stream);
		byte[] bytes = stream.toByteArray();
		fos.write(bytes);
		fos.close();
		return file;
	}

	/**
	 * 写图片文件到SD卡
	 * 
	 * @throws IOException
	 */
	public static void saveImageToSD(Context ctx, String filePath,
                                     Bitmap bitmap, int quality) throws IOException {
		if (bitmap != null) {
			File file = new File(filePath.substring(0,
					filePath.lastIndexOf(File.separator)));
			if (!file.exists()) {
				file.mkdirs();
			}
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(filePath));
			bitmap.compress(CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();
			if(ctx!=null){
				scanPhoto(ctx, filePath);
			}
		}
	}
	
	/**
	 * 将图片压缩后另存
	 * @param context
	 * @param pathName 图片文件
	 * @param width 限定宽度
	 * @param height 限定高度
	 * @return
	 */
	public static File compressImage(Context context, String pathName, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    // 获取这个图片的宽和高
	    BitmapFactory.decodeFile(pathName, options);
//	    System.out.println(String.format("原图大小：%d * %d", options.outWidth, options.outHeight));
	    int wRation = (int) Math.ceil(options.outWidth/(float)width);
        int hRation = (int) Math.ceil(options.outHeight/(float)height);
        if(hRation > 1 || wRation > 1){
        	options.inSampleSize = Math.max(wRation, hRation);
        	options.inJustDecodeBounds = false;
        	options.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
        	options.inPurgeable =true;// 同时设置才会有效
        	options.inInputShareable = true;// 当系统内存不够时候图片自动被回收
    	    Bitmap source = BitmapFactory.decodeFile(pathName, options);
    	    File file = new File(pathName);
    	    try {
				file = saveImage(context, file.getName() + ".tmp", source);
				return file;
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return new File(pathName);
	}
	
	/**
	 * 让Gallery上能马上看到该图片
	 */
	public static void scanPhoto(Context ctx, String imgFileName) {
		File file = new File(imgFileName);
//		Uri contentUri = Uri.fromFile(file);
		Uri contentUri = URIutil.getFileUri(ctx,file);
		scanPhoto(ctx, contentUri);
	}
	
	public static void scanPhoto(Context ctx, File path) {
//		Uri contentUri = Uri.fromFile(path);
		Uri contentUri = URIutil.getFileUri(ctx,path);
		scanPhoto(ctx, contentUri);
	}
	
	public static void scanPhoto(Context ctx, Uri uri) {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		mediaScanIntent.setData(uri);
		ctx.sendBroadcast(mediaScanIntent);
	}
	
	public static File sdCameraPath() {
		File path = new File(Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DCIM +
				File.separator + "Camera");
		path.mkdirs();
		return path;
	}
	
	public static Bitmap getBitmap(Context context, String fileName) {
		FileInputStream fis = null;
		Bitmap bitmap = null;
		try {
			fis = context.openFileInput(fileName);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return bitmap;
	}
	
	/**
	 * 从资源中加载图片，缩放后的大小不超过指定大小
	 * @param res
	 * @param resId
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap loadImage(Resources res, int resId, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    // 获取这个图片的宽和高
	    BitmapFactory.decodeResource(res, resId, options);
//	    System.out.println(String.format("原图大小：%d * %d", options.outWidth, options.outHeight));
	    int wRation = (int) Math.ceil(options.outWidth/(float)width);
        int hRation = (int) Math.ceil(options.outHeight/(float)height);
        if(hRation > 1 || wRation > 1){
        	options.inSampleSize = Math.min(wRation, hRation);
        } else
        	options.inSampleSize = 1;
	    options.inJustDecodeBounds = false;
	    Bitmap source = BitmapFactory.decodeResource(res, resId, options);
	    return source;
	}
	
	public static Bitmap loadImage(Resources res, int resId, int width) {
		BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    // 获取这个图片的宽和高
	    BitmapFactory.decodeResource(res, resId, options);
//	    System.out.println(String.format("原图大小：%d * %d", options.outWidth, options.outHeight));
	    int wRation = (int) Math.ceil(options.outWidth/(float)width);
        if(wRation > 1){
        	options.inSampleSize = wRation;
        } else
        	options.inSampleSize = 1;
	    options.inJustDecodeBounds = false;
	    Bitmap source = BitmapFactory.decodeResource(res, resId, options);
	    return source;
	}
	
	public static Bitmap loadImage(String pathName, int width, int height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    // 获取这个图片的宽和高
	    BitmapFactory.decodeFile(pathName, options);
//	    System.out.println(String.format("原图大小：%d * %d", options.outWidth, options.outHeight));
	    int wRation = (int) Math.ceil(options.outWidth/(float)width);
        int hRation = (int) Math.ceil(options.outHeight/(float)height);
        if(hRation > 1 || wRation > 1){
        	options.inSampleSize = Math.min(wRation, hRation);
        } else
        	options.inSampleSize = 1;
	    options.inJustDecodeBounds = false;
	    Bitmap source = BitmapFactory.decodeFile(pathName, options);
	    return source;
	}
	
	public static Bitmap loadImage(String pathName, int width) {
		BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    // 获取这个图片的宽和高
	    BitmapFactory.decodeFile(pathName, options);
//	    System.out.println(String.format("原图大小：%d * %d", options.outWidth, options.outHeight));
	    int wRation = (int) Math.ceil(options.outWidth/(float)width);
        if(wRation > 1){
        	options.inSampleSize = wRation;
        } else
        	options.inSampleSize = 1;
	    options.inJustDecodeBounds = false;
	    Bitmap source = BitmapFactory.decodeFile(pathName, options);
	    return source;
	}
	
	/**
	 * 从资源中加载图片，等比缩放后再按指定大小剪裁
	 * @param res
	 * @param resId
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap clipImage(Resources res, int resId, int width, int height) {
	    Bitmap source = loadImage(res, resId, width, height);
	    return clipImage(source, width, height);
	}
	
	/**
	 * 等比缩放后再按指定大小剪裁
	 * @param bmp
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap clipImage(Bitmap bmp, int width, int height) {
	    float scaleWidth = ((float) width / bmp.getWidth());  
	    float scaleHeight = ((float) height / bmp.getHeight());
	    float scale = Math.max(scaleWidth, scaleHeight);
	    int destWidth = (int) (bmp.getWidth() * scale);
	    int destHeight = (int) (bmp.getHeight() * scale);
	    Bitmap source = Bitmap.createScaledBitmap(bmp, destWidth, destHeight, true);
//	    System.out.println(String.format("缩放后大小：%d * %d", source.getWidth(), source.getHeight()));
	    width = Math.min(source.getWidth(), width);
	    height = Math.min(source.getHeight(), height);
	    Bitmap ret = Bitmap.createBitmap(source, 0, 0, width, height);
//	    System.out.println(String.format("剪切后大小：%d * %d", ret.getWidth(), ret.getHeight()));
	    return ret;
	}
	
	/**
	 * 转换图片成圆角图片
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public static Bitmap toRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
  
        final int color = 0xff424242;  
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;               //圆角  
  
        paint.setAntiAlias(true);  
        canvas.drawARGB(0, 0, 0, 0);  
        paint.setColor(color);  
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  
  
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  //Mode.SRC_IN 用前面画的“圆角矩形”对bitmap进行裁剪。
        canvas.drawBitmap(bitmap, rect, rect, paint);  
  
        return output;  
    }
	
    /**
     * 转换图片成圆形
     * @param bitmap 传入Bitmap对象
     * @return
     */
	public static Bitmap toCircleBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}
	
	public static Bitmap toGrayBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap grayImg = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(grayImg);

        Paint paint = new Paint();
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(colorMatrix);
        paint.setColorFilter(colorMatrixFilter);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return grayImg;
	}

	public static Bitmap toAlphaBitmap(Bitmap bitmap, int alpha) {
		int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        if (alpha < 0)
        	alpha = -alpha;
        if (alpha > 255)
        	alpha = alpha % 255;
        Bitmap blurImg = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blurImg);

        Paint paint = new Paint();
        paint.setAlpha(alpha);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return blurImg;
	}

//	public static Bitmap clipReceiveMaskImage(Resources res, Bitmap pic) {
//		return toMaskImage(res, pic, R.drawable.receive_pic_mask);
//	}
//
//	public static Bitmap clipSendMaskImage(Resources res, Bitmap pic) {
//		return toMaskImage(res, pic, R.drawable.send_pic_mask);
//	}

	/**
	 * 从9.png生成遮罩图片
	 * @param res
	 * @param pic
	 * @param maskResId
	 * @return
	 */
	public static Bitmap toMaskImage(Resources res, Bitmap pic, int maskResId) {
		int width = pic.getWidth();
		int height = pic.getHeight();
		Bitmap mask = BitmapFactory.decodeResource(res, maskResId);
		byte[] chunk = mask.getNinePatchChunk();
		if (!NinePatch.isNinePatchChunk(chunk))
			return pic;
		NinePatchDrawable npDrawable = new NinePatchDrawable(res, mask, chunk,
				NinePatchChunk.deserialize(chunk).mPaddings, null);
		mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(mask);
		canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG));
		npDrawable.setBounds(0, 0, width, height);
		npDrawable.draw(canvas);

        Bitmap temp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(temp);
        canvas.drawBitmap(pic, 0, 0, null);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //设置两张图片相交时的模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(null);

        width = width + 2;
        height = height + 2;
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(result);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG));
		npDrawable.setBounds(0, 0, width, height);
		npDrawable.draw(canvas);
		canvas.drawBitmap(temp, 1, 1, null);

        return result;
	}

	public static class NinePatchChunk {

	    public static final int NO_COLOR = 0x00000001;
	    public static final int TRANSPARENT_COLOR = 0x00000000;

	    public final Rect mPaddings = new Rect();

	    public int mDivX[];
	    public int mDivY[];
	    public int mColor[];

	    private static void readIntArray(final int[] data, final ByteBuffer buffer) {
	        for (int i = 0, n = data.length; i < n; ++i)
	            data[i] = buffer.getInt();
	    }

	    private static void checkDivCount(final int length) {
	        if (length == 0 || (length & 0x01) != 0)
	            throw new RuntimeException("invalid nine-patch: " + length);
	    }

	    public static NinePatchChunk deserialize(final byte[] data) {
	        final ByteBuffer byteBuffer =
	            ByteBuffer.wrap(data).order(ByteOrder.nativeOrder());

	        if (byteBuffer.get() == 0) return null; // is not serialized

	        final NinePatchChunk chunk = new NinePatchChunk();
	        chunk.mDivX = new int[byteBuffer.get()];
	        chunk.mDivY = new int[byteBuffer.get()];
	        chunk.mColor = new int[byteBuffer.get()];

	        checkDivCount(chunk.mDivX.length);
	        checkDivCount(chunk.mDivY.length);

	        // skip 8 bytes
	        byteBuffer.getInt();
	        byteBuffer.getInt();

	        chunk.mPaddings.left = byteBuffer.getInt();
	        chunk.mPaddings.right = byteBuffer.getInt();
	        chunk.mPaddings.top = byteBuffer.getInt();
	        chunk.mPaddings.bottom = byteBuffer.getInt();

	        // skip 4 bytes
	        byteBuffer.getInt();

	        readIntArray(chunk.mDivX, byteBuffer);
	        readIntArray(chunk.mDivY, byteBuffer);
	        readIntArray(chunk.mColor, byteBuffer);

	        return chunk;
	    }
	}

	 private static Bitmap getViewBitmapWithoutBottom(View v) {
	        if (null == v) {
	            return null;
	        }
	        v.setDrawingCacheEnabled(true);
	        v.buildDrawingCache();
	        if (Build.VERSION.SDK_INT >= 11) {
	            v.measure(View.MeasureSpec.makeMeasureSpec(v.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(v.getHeight(), View.MeasureSpec.EXACTLY));
	            v.layout((int) v.getX(), (int) v.getY(), (int) v.getX() + v.getMeasuredWidth(), (int) v.getY() + v.getMeasuredHeight());
	        } else {
	            v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
	            v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
	        }
	        Bitmap bp = Bitmap.createBitmap(v.getDrawingCache(), 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight() - v.getPaddingBottom());
	        v.setDrawingCacheEnabled(false);
	        v.destroyDrawingCache();
	        return bp;
	    }

	    public static Bitmap getViewBitmap(View v) {
	        if (null == v) {
	            return null;
	        }
	        v.setDrawingCacheEnabled(true);
	        v.buildDrawingCache();
	        if (Build.VERSION.SDK_INT >= 11) {
	            v.measure(View.MeasureSpec.makeMeasureSpec(v.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(v.getHeight(), View.MeasureSpec.EXACTLY));
	            v.layout((int) v.getX(), (int) v.getY(), (int) v.getX() + v.getMeasuredWidth(), (int) v.getY() + v.getMeasuredHeight());
	        } else {
	            v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
	            v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
	        }
	        Bitmap b = Bitmap.createBitmap(v.getDrawingCache(), 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
	        v.setDrawingCacheEnabled(false);
	        v.destroyDrawingCache();
	        return b;
	    }

	    /**
	     * 获取 WebView 视图截图
	     * @param context
	     * @param view
	     * @return
	     */
	    public static Bitmap getWebViewBitmap(Context context, WebView view) {
	        if (null == view) return null;
	        view.scrollTo(0, 0);
	        view.buildDrawingCache(true);
	        view.setDrawingCacheEnabled(true);
	        view.setVerticalScrollBarEnabled(false);
	        Bitmap b = getViewBitmapWithoutBottom(view);
	        // 可见高度
	        int vh = view.getHeight();
	        // 容器内容实际高度
	        int th = (int)(view.getContentHeight()*view.getScale());
	        Bitmap temp = null;
	        if (th > vh) {
	            int w = getScreenWidth(context);
	            int absVh = vh - view.getPaddingTop() - view.getPaddingBottom();
	            do {
	                int restHeight = th - vh;
	                if (restHeight <= absVh) {
	                    view.scrollBy(0, restHeight);
	                    vh += restHeight;
	                    temp = getViewBitmap(view);
	                } else {
	                    view.scrollBy(0, absVh);
	                    vh += absVh;
	                    temp = getViewBitmapWithoutBottom(view);
	                }
	                b = mergeBitmap(vh, w, temp, 0, view.getScrollY(), b, 0, 0);
	            } while (vh < th);
	        }
	        // 回滚到顶部
	        view.scrollTo(0, 0);
	        view.setVerticalScrollBarEnabled(true);
	        view.setDrawingCacheEnabled(false);
	        view.destroyDrawingCache();
	        return b;
	    }

	    /**
	     * 拼接图片
	     * @param newImageH
	     * @param newImageW
	     * @param background
	     * @param backX
	     * @param backY
	     * @param foreground
	     * @param foreX
	     * @param foreY
	     * @return
	     */
	    private static Bitmap mergeBitmap(int newImageH, int newImageW, Bitmap background, float backX, float backY, Bitmap foreground, float foreX, float foreY) {
	        if (null == background || null == foreground) {
	            return null;
	        }
	        Bitmap bitmap = Bitmap.createBitmap(newImageW, newImageH, Bitmap.Config.RGB_565);
	        Canvas cv = new Canvas(bitmap);
	        cv.drawBitmap(background, backX, backY, null);
	        cv.drawBitmap(foreground, foreX, foreY, null);
	        cv.save(Canvas.ALL_SAVE_FLAG);
	        cv.restore();
	        return bitmap;
	    }

	    /**
	     * get the width of screen
	     */
	    public static int getScreenWidth(Context ctx) {
	        int w = 0;
	        if (Build.VERSION.SDK_INT > 13) {
	            Point p = new Point();
	            ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(p);
	            w = p.x;
	        } else {
	            w = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
	        }
	        return w;
	    }

	    /**
	     * 保存图片
	     * @param context
	     * @param bitmap
	     * @param file
	     * @param quality
	     * @return
	     */
	    public static boolean save(Context context, Bitmap bitmap, File file, int quality) {
	        if (bitmap == null) return false;
	        // 获得后缀格式
	        String abs = file.getAbsolutePath();
	        String suffix = abs.substring(abs.lastIndexOf(".")+1).toLowerCase();
	        Bitmap.CompressFormat format;
	        if ("jpg".equals(suffix) || "jpeg".equals(suffix)) {
	            format = Bitmap.CompressFormat.JPEG;
	        } else {
	            format = Bitmap.CompressFormat.PNG;
	            quality = 100;
	        }
	        if (file.exists() && ! file.delete()) return false;
	        try {
	            FileOutputStream stream = new FileOutputStream(file);
	            bitmap.compress(format, quality, stream);
	            stream.flush();
	            stream.close();
	            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	    }
}
